<template>
  <div class="write-askleave">
    <!-- 操作結果提示 -->
    <msg v-if="doneShow" class="done-msg" :icon="doneIcon">
      <template slot="buttons">
        <router-link class="success-btn" v-if="doneIcon === 'success'" :to="{ name: 'InitiateApplication'}">
          返回首页
        </router-link>
        <a class="success-btn" v-else @click="closeDoneInfo">返回请假申请</a>
      </template>
      <template slot="description">
        <p class="title">{{doneTitle}}</p>
        <p>{{doneMsg}}</p>
      </template>
    </msg>
    <div class="scroll-box" v-show="!doneShow">
      <!-- 請假信息填寫 -->
      <my-ask-leave-info ref="askLeaveInfo"></my-ask-leave-info>
      <!-- 審批人 -->
      <!-- <my-approver ref="approver"></my-approver> -->
      <!-- 抄送人 -->
      <my-make-copy ref="makeCopy" :makeCopyParams="makeCopyParams"></my-make-copy>
    </div>
    <!-- 底部組件 -->
    <my-bottom-submit v-if="!doneShow" @click.native="applySubmit"></my-bottom-submit>
    <!-- 加载中 -->
    <loading class="loading-mask" :show="loadingShow" text="加载中..."></loading>
    <!-- 提示彈窗 -->
    <div v-transfer-dom>
      <confirm v-model="turndownShow"
        class="turndown-confirm turndown-alert" title="提示" confirm-text="确认" :show-cancel-button="false">
        <p>{{turndownText}}</p>
      </confirm>
    </div>
  </div>
</template>

<script>
  import AskLeaveInfo from '@/components/ApplyWrite/AskLeaveInfo.vue';
  // import Approver from '@/components/ApplyWrite/Approver.vue';
  import MakeCopy from '@/components/ApplyWrite/MakeCopy.vue';
  import BottomSubmit from '@/components/Bottom/BottomSubmit.vue';
  import { Msg, Loading, Confirm, TransferDom } from 'vux';
  import qs from 'qs';
  export default {
    name: 'WriteAskLeave',
    data () {
      return {
        defaultMakeCopyStaffNo01:'1607245',
        defaultMakeCopyStaffNo02:'1911926',
        defaultMakeCopyStaffNo03:'2003036',
        doneIcon: '',
        doneTitle: '',
        doneMsg: '',
        doneShow: false,
        loadingShow: false,
        required: ['StartDate', 'EndDate', 'Minute', 'Reason', 'Type'],
        turndownShow: false,
        turndownText: '',
        makeCopyParams: []
      };
    },
    directives: {
      TransferDom
    },
    components: {
      Msg,
      Loading,
      Confirm,
      'my-ask-leave-info': AskLeaveInfo,
      // 'my-approver': Approver,
      'my-make-copy': MakeCopy,
      'my-bottom-submit': BottomSubmit
    },
   
    async mounted () {
      await this.pageInit();
      if (this.$refs.makeCopy.resultList.length === 0) {
        this.$refs.makeCopy.resultList = this.makeCopyParams;
      }
    },
    watch: {
      $route (to, from) {
        setTimeout(() => {
          this.loadingShow = false;
          this.changeDoneInfo(false);
        }, 500);
        this.pageInit(to, from);
      }
    },
    methods: {
      applySubmit: function () {
        if (this.loadingShow) {
          return false;
        }
        let ContentData = {
          Images: this.$refs.askLeaveInfo.imagesList,
          Reason: this.$refs.askLeaveInfo.reasonText,
          StartDate: this.$refs.askLeaveInfo.startDate,
          EndDate: this.$refs.askLeaveInfo.endDate,
          Minute: this.$refs.askLeaveInfo.applyMinute,
          Day: this.$refs.askLeaveInfo.applyDay,
          Type: this.$refs.askLeaveInfo.applyType,
          Other: this.$refs.askLeaveInfo.otherTypeReason
        };
        if (this.$refs.askLeaveInfo.changeApplyType === '重新申请原因') {
          ContentData.ReApplyReason = this.$refs.askLeaveInfo.reApplyReason;
        }
        if (this.$refs.askLeaveInfo.changeApplyType === '修改申请原因') {
          ContentData.EditApplyReason = this.$refs.askLeaveInfo.editApplyReason;
        }
        // 需要post的數據
        let postData = {
          data: {
            Type: 1,
            CreatedStaffNo: this.getUserInfo().StaffNo,
            Copiers: this.parseCopiers(),
            Content: JSON.stringify(ContentData)
          }
        };
        for (let prop in this.required) {
          let propName = this.required[prop];
          if (ContentData[propName] === '') {
            this.turndownText = '请输入必填项';
            this.turndownShow = true;
            return false;
          }
        }
        if (!this.checkDate(ContentData.StartDate, ContentData.EndDate, ContentData.Type)) {
          return false;
        }
        if (this.isHasImage() === false) {
          return false;
        }
        if (this.checkMinute(ContentData.Minute) === false) {
          return false;
        }
        if (this.$route.query && this.$route.query.titleName === '修改申请') {
          postData.data.KeyId = JSON.parse(this.$route.query.applyInfo).KeyId;
          this.editRequest(postData);
        } else {
          if (this.$route.query.applyInfo !== undefined) {
            let query = JSON.parse(this.$route.query.applyInfo);
            if (query.IsReApply !== undefined) {
              postData.data.IsReApply = query.IsReApply;
            }
          }
          this.createRequest(postData);
        }
      },
      editRequest: function (params) {
        this.loadingShow = true;
        this.axios.post('/Process/EditAskForLeaveInfo', qs.stringify(params))
        .then((res) => {
          if (res.data.IsSuccess === true) {
            this.loadingShow = false;
            this.changeDoneInfo(true, 'success', '提交修改成功', '你的申请已成功提交修改，等待上级领导审批中');
          } else {
            this.loadingShow = false;
            this.changeDoneInfo(true, 'warn', '提交修改失败', `你的申請未能成功提交修改，具体错误：${res.data.ExMessage}`);
          }
        })
        .catch((err) => {
          this.loadingShow = false;
          this.changeDoneInfo(true, 'warn', '提交修改失败', `你的申請未能成功提交修改，具体错误：${err}`);
        });
      },
      createRequest: function (params) {
        this.loadingShow = true;
        this.axios.post('/Process/Create', qs.stringify(params))
        .then((res) => {
          if (res.data.IsSuccess === true) {
            this.loadingShow = false;
            this.changeDoneInfo(true, 'success', '提交申请成功', '你的申请已成功提交，等待上级领导审批中');
          } else {
            this.loadingShow = false;
            this.changeDoneInfo(true, 'warn', '提交申请失败', `你的申请未能成功提交，具体错误：${res.data.ExMessage}`);
          }
        })
        .catch((err) => {
          this.loadingShow = false;
          this.changeDoneInfo(true, 'warn', '提交申请失败', `你的申请未能成功提交，具体错误：${err}`);
        });
      },
      // 抄送人格式轉換 （只POST StaffNo）
      parseCopiers: function () {
        let copiers = this.$refs.makeCopy.resultList;
        let newCopiers = [];
        copiers.forEach((item) => {
          newCopiers.push({StaffNo: item.userid});
        });
        return newCopiers;
      },
      changeDoneInfo: function (status, iconType, title, msg) {
        this.doneIcon = iconType;
        this.doneTitle = title;
        this.doneMsg = msg;
        this.doneShow = status;
      },
      closeDoneInfo: function () {
        this.changeDoneInfo(false, '', '', '');
      },
      // 檢測請假分鐘是否0
      checkMinute: function (minute) {
        if (minute === 0) {
            this.turndownText = '请假时数不能为0';
            this.turndownShow = true;
          return false;
        } else {
          return true;
        }
      },
      // 检查病假是否有上传图片
      isHasImage: function () {
        if (this.$refs.askLeaveInfo.applyTypeCode.indexOf('病假') !== -1) {
          if (this.$refs.askLeaveInfo.imagesList.length > 0) {
            return true;
          } else {
            this.turndownText = '病假必须上传病假证明';
            this.turndownShow = true;
            return false;
          }
        } else {
          return true;
        }
      },
      // 提交时检查日期是否符合请假类型要求的提前申请日期
      checkDate: function (startDate, endDate, type) {
        let typeKV = this.getTypeKeyValue();
        let typeValue = typeKV.filter(x => x.KeyId === type)[0].ItemValue;
        let res = null;
        let msg = '';
        if (typeValue === '3' || typeValue === '5') {
          res = this.checkDateAdvance(startDate, endDate, 3);
          msg = '必须3日前完成审批';
        } else if (typeValue === '2') {
          res = this.checkDateAdvance(startDate, endDate, 15);
          msg = '必须15日前完成审批';
        } else {
          res = { status: true };
        }
        if (!res.status) {
          this.turndownShow = true;
          this.turndownText = `${msg}，请假开始或结束日期不符合要求`;
          return false;
        }
        return true;
      },
      // 檢查日期是否符合請假類型要求提前的天數
      checkDateAdvance: function (startDateStr, endDateStr, AdvanceDays) {
        let todayDate = new Date();
        todayDate.setHours(0);
        todayDate.setMinutes(0);
        todayDate.setSeconds(0);
        let advanceDateTimeStamp = new Date(todayDate.getTime() + AdvanceDays * 86400000);
        if (startDateStr !== '') {
          let startDate = new Date(startDateStr.replace(/ /g, 'T'));
          if (startDate.getTime() <= advanceDateTimeStamp) {
            return {
              errorDate: 'startDate',
              advanceDateTimeStamp: advanceDateTimeStamp,
              message: `必须提前${AdvanceDays}天申请，请假开始或结束日期不符合要求`,
              status: false
            };
          }
        }
        if (endDateStr !== '') {
          let endDate = new Date(endDateStr.replace(/ /g, 'T'));
          if (endDate.getTime() <= advanceDateTimeStamp) {
            return {
              errorDate: 'endDate',
              advanceDateTimeStamp: advanceDateTimeStamp,
              message: `请假结束日期必须提前${AdvanceDays}天`,
              status: false
            };
          }
        }
        return {
          advanceDateTimeStamp: advanceDateTimeStamp,
          status: true
        };
      },
      getDefaultMakeCopy:async function () {
        let postData = {
          data: {
            StaffNoArr:[
              {StaffNo:this.defaultMakeCopyStaffNo01},
              {StaffNo:this.defaultMakeCopyStaffNo02},
              {StaffNo:this.defaultMakeCopyStaffNo03}
              ]
          }
        };
        this.loadingShow = true;
        try {
          let res = await this.axios.post('/Wechat/QueryUsersFromStaffNo', qs.stringify(postData))
          this.loadingShow = false;
          if (res.data.IsSuccess === true) {
            for(var item of res.data.data.Users){
              item["checked"] = true;
              item["removeSwitch"] = false;
            }
            let makeCopyArr = res.data.data.Users;
            return makeCopyArr;
          } else {
            this.turndownShow = true;
            this.turndownText = '获取默认抄送人失败';
            return [];
          }
        } catch(err){
          this.loadingShow = false;
          this.turndownShow = true;
          this.turndownText = '获取默认抄送人失败';
          console.log(err)
          return [];
        }
        
        
        // return [
          // {
          //   'userid': '10920',
          //   'name': 'PER Mandy Ma',
          //   'department': [12, 14, 5],
          //   'position': '人力資源、牌照及培訓部主任',
          //   'mobile': '+85362038068',
          //   'gender': 2,
          //   'email': '',
          //   'weixinid': null,
          //   'avatar': 'http://p.qpic.cn/wwhead/duc2TvpEgSTPk74IwG7Bs6sAucPaKZBlIRIvvq5CPph1sU1O6jHM91JsShDQvTs4xmSMxd5fjwA/0',
          //   'status': 1,
          //   'extattr': {
          //     'attrs': []
          //   },
          //   'checked': true,
          //   'removeSwitch': false
          // },
          // {
          //   'userid': '11461',
          //   'name': 'PER Stephanie Fong',
          //   'department': [5, 1, 14],
          //   'position': '人力資源部文員',
          //   'mobile': '+85366477966',
          //   'gender': 2,
          //   'email': '',
          //   'weixinid': null,
          //   'avatar': 'http://p.qlogo.cn/bizmail/VQJ0TWibRu6NxurZPQ0IVrNQra6BFrIib1uE4yaXYKXzuK8szI3ZXHVw/',
          //   'status': 1,
          //   'extattr': {
          //     'attrs': [
          //       {
          //         'name': '英文名',
          //         'value': '',
          //         'type': 0,
          //         'text': {
          //           'value': ''
          //         }
          //       }
          //     ]
          //   },
          //   'checked': true,
          //   'removeSwitch': false
          // }
        // ];
      },
      getReApplyMakeCopy: function (staffNoArr) {
        if (staffNoArr.length === 0) {
          return false;
        }
        let postData = {
          data: {
            StaffNoArr: staffNoArr
          }
        };
        this.loadingShow = true;
        return this.axios.post('/Wechat/QueryUsersFromStaffNo', qs.stringify(postData))
        .then((res) => {
          this.loadingShow = false;
          if (res.data.IsSuccess === true) {
            this.makeCopyParams = this.makeCopyParams.concat(res.data.data.Users);
            this.$refs.makeCopy.resultList = this.makeCopyParams;
          } else {
            this.turndownShow = true;
            this.turndownText = '获取抄送人失败';
          }
        })
        .catch(() => {
          this.loadingShow = false;
          this.turndownShow = true;
          this.turndownText = '获取抄送人失败';
        });
      },
      pageInit:async function (to, from) {
        let isHomeToThisPage;
        if (to && from) {
          isHomeToThisPage = from.name === 'InitiateApplication' && this.$route.name === 'WriteAskLeave';
        }
        let isReApplyToThisPage = this.$route.query.applyInfo;
        if (isHomeToThisPage) {
          this.$refs.askLeaveInfo.startDate = '';
          this.$refs.askLeaveInfo.endDate = '';
          this.$refs.askLeaveInfo.applyTimeText = '';
          this.$refs.askLeaveInfo.applyMinute = '';
          this.$refs.askLeaveInfo.applyDay = '';
          this.$refs.askLeaveInfo.reasonText = '';
          // this.$refs.makeCopy.resultList = [];
          this.$refs.askLeaveInfo.imagesList = [];
          this.$refs.askLeaveInfo.imagesUploadList = [];
          this.$refs.askLeaveInfo.previewerImagesList = [];
          this.$refs.askLeaveInfo.applyType = '';
          this.$refs.askLeaveInfo.otherTypeReason = '';
          this.$refs.askLeaveInfo.otherInputPlaceholder = '';
          this.$refs.askLeaveInfo.otherTypeDisabled = true;
          this.$refs.askLeaveInfo.applyTypeCode = '';
          this.$refs.askLeaveInfo.datePickerConfig = {
            format: 'YYYY-MM-DD HH:mm', // 日期格式
            workEndHour: 19, // 下班時間
            workStartHour: 9, // 上班時間
            startDateConfig: {
              startDate: '',
              endDate: '',
              minuteList: ['00', '15', '30', '45']
            },
            endDateConfig: {
              startDate: '',
              endDate: '',
              minuteList: ['00', '15', '30', '45']
            }
          };
          this.required.pop();
          this.makeCopyParams = await this.getDefaultMakeCopy();
          this.$refs.askLeaveInfo.changeApplyType = '';
        } else if (from && from.name === 'SelectPerson' && this.$route.name === 'WriteAskLeave') {
        } else if (isReApplyToThisPage && this.$route.name === 'WriteAskLeave') {
          let params = JSON.parse(isReApplyToThisPage);
          // console.log(params.Content);
          // console.log(params.Content.Reason);
          let startDate = params.Content.StartDate;
          let endDate = params.Content.EndDate;
          this.makeCopyParams = await this.getDefaultMakeCopy();
          let copiers = params.Copiers.slice(3, params.Copiers.length); // 正式
          // let copiers = params.Copiers; // 测试
          if (copiers.length !== 0) {
            this.getReApplyMakeCopy(copiers);
          }
          setTimeout(() => {
            this.$refs.askLeaveInfo.startDate = startDate.slice(0, startDate.lastIndexOf(':')).replace(/T/g, ' ');
            this.$refs.askLeaveInfo.endDate = endDate.slice(0, endDate.lastIndexOf(':')).replace(/T/g, ' ');
            this.$refs.askLeaveInfo.applyTypeChange(this.getTypeKeyValueFromKeyId(params.Content.Type));
          }, 0);
          this.$refs.askLeaveInfo.applyTimeText = `${((params.Content.Minute)/60).toFixed(2)}小时（共${params.Content.Day}天）`;
          this.$refs.askLeaveInfo.applyMinute = params.Content.Minute;
          this.$refs.askLeaveInfo.applyDay = params.Content.Day;
          this.$refs.askLeaveInfo.reasonText = params.Content.Reason;
          this.$refs.askLeaveInfo.imagesList = params.Content.Images;
          this.$refs.askLeaveInfo.imagesUploadList = [];
          this.$refs.askLeaveInfo.previewerImagesList = [];
          this.$refs.askLeaveInfo.applyType = params.Content.Type;
          this.$refs.askLeaveInfo.otherTypeReason = params.Content.Other;
          this.$refs.askLeaveInfo.otherInputPlaceholder = '';
          this.$refs.askLeaveInfo.otherTypeDisabled = true;
          this.$refs.askLeaveInfo.applyTypeCode = '';
          if (this.$route.query.titleName === '修改申请') {
            // this.$refs.askLeaveInfo.reApplyReasonShow = true;
            this.$refs.askLeaveInfo.editApplyReason = '';
            this.required.push('EditApplyReason');
            this.$refs.askLeaveInfo.changeApplyType = '修改申请原因';
          } else if (params.IsReApply === true) {
            this.$refs.askLeaveInfo.reApplyReason = '';
            this.required.push('ReApplyReason');
            this.$refs.askLeaveInfo.changeApplyType = '重新申请原因';
          }
        } else {
          this.makeCopyParams = await this.getDefaultMakeCopy();
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  @import '../../assets/style/variable';
  .write-askleave{
    -webkit-overflow-scrolling: touch;
  }
</style>
